﻿using SolidWorks.Interop.sldworks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SolidworksDLL
{
    public class ModelDocHelp
    {


        public static PartDoc GetPartDoc(ModelDoc2 myModelDoc)
        {
            if (myModelDoc == null)
            {
                return null;
            }
            if (myModelDoc.GetType() != 1)
            {
                return null;

            }
            else
            {
                return (PartDoc)myModelDoc;
            }
        }

        public static AssemblyDoc GetAsmDoc(ModelDoc2 myModelDoc)
        {
            if (myModelDoc == null)
            {
                return null;
            }
            if (myModelDoc.GetType() != 2)
            {
                return null;

            }
            else
            {
                return (AssemblyDoc)myModelDoc;
            }
        }

        public static DrawingDoc GetDrawDoc(ModelDoc2 myModelDoc)
        {
            if (myModelDoc == null)
            {
                return null;
            }
            if (myModelDoc.GetType() != 3)
            {
                return null;

            }
            else
            {
                return (DrawingDoc)myModelDoc;
            }
        }

        /// <summary>
        /// 使用指定模板创建新零件
        /// </summary>
        /// <param name="tempPath">模板路径</param>
        /// <returns>零件模型对象</returns>
        public static PartDoc NewPart(string tempPath)
        {
            if (SolidWorksHelp.SwApp == null)
            {
                MessageBox.Show("请先连接到SW对象");
            }

            ModelDoc2 swModel = SolidWorksHelp.SwApp.NewDocument(tempPath ,0,0,0);
            return GetPartDoc(swModel);
        }

        public static AssemblyDoc NewAsm(string tempPath)
        {
            if (SolidWorksHelp.SwApp == null)
            {
                MessageBox.Show("请先连接到SW对象");
            }

            ModelDoc2 swModel = SolidWorksHelp.SwApp.NewDocument(tempPath, 0, 0, 0);
            return GetAsmDoc(swModel);
        }

        public static DrawingDoc NewDraw(string tempPath)
        {
            if (SolidWorksHelp.SwApp == null)
            {
                MessageBox.Show("请先连接到SW对象");
            }

            ModelDoc2 swModel = SolidWorksHelp.SwApp.NewDocument(tempPath, 0, 0, 0);
            return GetDrawDoc(swModel);
        }

        /// <summary>
        /// 给定模板路径，创建模型文档
        /// </summary>
        /// <param name="tempPath">模板路径</param>
        /// <returns>成功返回空字符串，失败返回原因</returns>
        public static string NewDocumnet(string tempPath)
        {
            if (File.Exists(tempPath) == false)       // 检查文件是否存在
            {
                return "模板路径" + tempPath +   "不存在";

            }

            string extension =  Path.GetExtension(tempPath).ToUpper();  //ToUpper字母转为大写，ToLower 转小写

            if (".PRTDOT" == extension )                           
            {
                PartDoc part = NewPart(tempPath);
                if (part == null)
                {
                    return "创建零件失败";
                }
                else
                {
                    return "";
                }
            }
            else if (".ASMDOT" == extension)
            {
                AssemblyDoc part = NewAsm(tempPath);
                if (part == null)
                {
                    return "创建装配体失败";
                }
                else
                {
                    return "";
                }
            }
            else if (".DRWDOT" == extension)
            {
                DrawingDoc part = NewDraw(tempPath);
                if (part == null)
                {
                    return "创建工程图失败";
                }
                else
                {
                    return "";
                }
            }

            return "创建失败";

        }


        public static string SaveDoc( string NewFilePath, object ModelDoc = null)
        {
            if (ModelDoc == null)
            {
                ModelDoc = SolidWorksHelp.SwApp.ActiveDoc;
            }

            ModelDoc2 swModel = (ModelDoc2)ModelDoc;
            ModelDocExtension modelExt = swModel.Extension;
            return SaveDoc(modelExt, NewFilePath);
        }


        /// <summary>
        /// 获取当前激活的文件对象
        /// </summary>
        /// <returns></returns>
        public static string GetActiveDoc()
        {
            ModelDoc2 modelDoc = SolidWorksHelp.SwApp.ActiveDoc;

            if (modelDoc != null)
            {
                return modelDoc.GetPathName ();
            }
            return "当前文件为空";

        }

        /// <summary>
        /// 获取当前装配体在位编辑的文件对象
        /// </summary>
        /// <returns></returns>
        public static string GetEditTarget()
        {
            ModelDoc2 modelDoc = SolidWorksHelp.SwApp.ActiveDoc;

            if (modelDoc == null)
            {
                return "当前文件为空";
            }
            else
            { 
                if (modelDoc.GetType() !=2)
                {
                    return "当前文件不是装配体";
                }

                AssemblyDoc asmDoc = (AssemblyDoc)modelDoc;
                ModelDoc2 swModel = asmDoc.GetEditTarget();
                if (swModel == null)
                {
                    return "当前没用在位编辑的零件";
                }
                return swModel.GetPathName();
            }
            ;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="modelExt"></param>
        /// <param name="NewFilePath">保存路径</param>
        /// <returns>成功返回空字符串，失败返回错误信息</returns>
        public static string SaveDoc(ModelDocExtension modelExt,string NewFilePath)
        {
            int err = 0;
            int war = 0;
            bool b =  modelExt.SaveAs(NewFilePath, 0, 1,null,ref err,ref war);

            if (b == false || err != 0)
            {
                return "保存文档到：" + NewFilePath + "出现错误，错误代号：" + err.ToString();
            }
            return "";
        }


        /// <summary>
        /// 打开指定路径的SW文档
        /// </summary>
        /// <param name="FilePath">文件路径</param>
        /// <returns>成功返回空字符串，失败返回错误信息</returns>
        public static string OpenDoc(string FilePath)
        {
            string ext = Path.GetExtension(FilePath).ToUpper();
            string FileName = Path.GetFileName(FilePath);
            
            int type = 0;
            switch(ext)
            {
                case ".SLDPRT":
                    type = 1;
                    break;
                case ".SLDASM":
                    type = 2;
                    break;
                case ".SLDDRW":
                    type = 3;
                    break;
                case ".X_T":
                    type = 4;
                    break;
                case ".STP":
                    type = 4;
                    break;
                case ".STEP":
                    type = 4;
                    break;
                default:
                    break;
            }
            if (type == 0)
            {
                return "不是零件、装配体、工程图";
            }



            int err = 0;
            int war = 0;

            ModelDoc2 swModel = SolidWorksHelp.SwApp.ActivateDoc(FileName);      //
            if (swModel != null)
            {
                return "当前已打开文件：" + swModel.GetPathName();

            }

            if (type == 4)
            {
                string FilePathName = Path.GetDirectoryName(FilePath);
                string Name = Path.GetFileNameWithoutExtension(FilePath);
                swModel = SolidWorksHelp.SwApp.LoadFile4(FilePath, "r", null, ref err);

                //MyDateTime = DateTime.Now.ToString("yyMMddHHmmss");
                SaveDoc(FilePathName + "\\" + Name+ ".SLDPRT");
            }
            else
            {
                swModel = SolidWorksHelp.SwApp.OpenDoc6(FilePath, type, 1, "", ref err, ref war);                 //LoadFile4打开其他格式文档
            }

            

            if (type == 2)
            {
                //MessageBox.Show("文件类型为" + type);
                AssemblyDoc swModel2 = (AssemblyDoc)swModel;
                swModel2.ResolveAllLightWeightComponents(false);
            }

            if (swModel == null)
            {
                return "打开文件：" + FilePath + "失败，错误代号：" + err.ToString();
            }
            else if (err != 0)
            {
                return "打开文件：" + FilePath + "错误，错误代号：" + err.ToString();
            }
            else
            {
                return "";
            }

        }


        /// <summary>
        /// 获取打开的所有文件路径（不包括轻化的零件）
        /// </summary>
        /// <returns>返回一个列表</returns>
        public static List<string>  GetAllDoc()
        {
            if (SolidWorksHelp .SwApp == null)
            {
                MessageBox.Show("请先连接到solidworks对象");
                return null;

            }
            List<string> modelPaths = new List<string>();

            int count = SolidWorksHelp.SwApp.GetDocumentCount();
            if (count == 0)
            {
                return modelPaths;
            }
            var swModels = (object[])SolidWorksHelp.SwApp.GetDocuments();
            
            foreach (ModelDoc2 item in swModels )
            {
                modelPaths.Add(item.GetPathName());
            }

            return modelPaths;

        }


    }
}
